package com.zhxy.util;

import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IoTool {
	
	/**
	 * 将input的数据直接写入到output中
	 * @param output 输出流
	 * @param input 输入流
	 * @return 成功读取并写入的字节数
	 * @throws IOException
	 */
	public static int copyStream(OutputStream output, InputStream input) throws IOException {
		
		int totalRead = 0;
		byte[] buffer = new byte[1024];
		
		while (true) {
			int r = input.read(buffer);
			if (r == -1)
				break;
			output.write(buffer, 0, r);
			totalRead += r;
		}
		
		return totalRead;
	}
	
	/**
	 * 关闭
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			closeable.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 刷新
	 * @param flushable
	 */
	public static void flush(Flushable flushable) {
		try {
			flushable.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 刷新后关闭
	 * @param output
	 */
	public static void flushClose(OutputStream output) {
		flush(output);
		close(output);
	}
}
